﻿using System;
using System.Data;
using System.Configuration;

namespace LearnNet.Common.RegExpression
{
    using System.Collections;
    using System.Text.RegularExpressions;
    /// <summary>
    ///  采用正则表达式方式表示的抽象基类
    /// </summary>
    public class RegExpressionBase: IRegExpression
    {
        protected Regex regex;
        /// <summary>
        /// 初始化正则，不区分大小写匹配
        /// </summary>
        /// <param name="expression"></param>
        public RegExpressionBase(string expression)
        {
            regex = new Regex(expression, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        }

        public virtual bool IsMatch(string context)
        {
            return regex.IsMatch(context);
        }

        /// <summary>
        /// 解析表达式
        /// </summary>
        /// <param name="context"></param>
        public virtual void Evaluate(RegContext context)
        {
            if (context == null) throw new ArgumentNullException("context is null!");
            switch (context.Operator)
            {
                case 'M':
                    EvaluateMatch(context);
                    break;
                case 'R':
                    EvaluateReplace(context);
                    break;
                default :
                    throw new ArgumentException("context.Operator is erorr");
            }
        }

        /// <summary>
        /// 通过Match方式解析表达式，可以被覆盖
        /// </summary>
        /// <param name="context"></param>
        protected virtual void EvaluateMatch(RegContext context)
        {
            context.Matches.Clear();
            MatchCollection coll = regex.Matches(context.Context);
            if (coll.Count == 0) return;
            foreach (Match match in coll)
            {
                context.Matches.Add(match.Value);
            }
        }

        /// <summary>
        /// 通过replace方法替换内容，可以被子类覆盖
        /// </summary>
        /// <param name="context"></param>
        protected virtual void EvaluateReplace(RegContext context)
        {
            context.Context = regex.Replace(context.Context, context.Replacement);
        }


    }

}
